package com.mactivity.activities;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.sql.Date;
import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import com.mactivity.database.PlanActivityFunctions;
import com.mactivity.helper.Constants;
import com.mactivity.helper.Messages;
import com.mactivity.helper.SharedPreferenceHelper;
import android.content.Intent;
import android.widget.DatePicker;


public class PlanEventActivity extends Activity implements OnClickListener, View.OnTouchListener {
    /** Called when the activity is first created. */
		
	private String sportType=null;
	private Date currentDate;
	private Date planDate=null;
	private String planTime=null;
	private TextView[] totalNumTable;	// column that show total attending number
	private TextView[] groupNumTable;	// column that show attend group member
	private String [] stringTimeTable;
	private Map<String, Integer> timeStringToIdMap;	// map a string to an id
	private Map<String, Integer> timeGroupToIdMap;
	private Map<Integer, Time> timeIdToTimeMap;			// map an id to time
	private SharedPreferenceHelper preferenceHelper = null;
	private Map<String, String> userInfo = null;
	private PlanActivityFunctions planFunction = new PlanActivityFunctions();
	private ArrayList<String> invitedFriendList = new ArrayList<String>();	// list of id that invited in to the group plan

	/**
	 * override the back button on the phone
	 */
	@Override
    public void onBackPressed() {
		if(sportType==null){	// on pick sport type page
			// clicking the back button on the phone will result going back to the home page
			Intent myIntent = new Intent(PlanEventActivity.this, HomeActivity.class);
			startActivity(myIntent);
			Log.d("Constants.", Messages.PLAN_ACTIVITY_CANCEL_PLAN);
			finish();
		}
		else if(planDate==null){	// on pick date page
			sportType=null;	// reset to null
			// go back to pick date page
			setContentView(R.layout.picktype);
		}
		else if (planTime==null){	// on pick time page
			planDate =null; // reset to null
			getDate();
		}
		else{	// confirmation page and pick friend page
			Intent myIntent = new Intent(PlanEventActivity.this, HomeActivity.class);
			startActivity(myIntent);
			Log.d("Constants.", Messages.PLAN_ACTIVITY_CANCEL_PLAN);
			finish();
		}
			
		
		
    }
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.picktype);       // call pick sport   
        
        preferenceHelper =  new SharedPreferenceHelper(this);
        userInfo=preferenceHelper.getUserInformation();
               
        Log.d(Constants.LOG_PLAN_TAG,
				Messages.PLAN_ACTVITY_START);
        matchTime();
    }
                
    /**
     * match view on the time
     */
    private void createOnTouchListener(){
    	// 24 hours a day
    	totalNumTable = new TextView[24];
    	groupNumTable = new TextView[24];
    	// initiation of the textview tables
    	for(int i=0;i<totalNumTable.length;i++){
    		totalNumTable[i] = new TextView(this);    
    		groupNumTable[i] = new TextView(this);
    	}
    	int num = 0, totalInvitedNum=0, acceptedNum=0, groupPlanId=0;
    	int[] groupIdList = new int[0];
    	for(int i =Constants.OPEN_HOUR; i<totalNumTable.length;i++){
    		// get the id for the view
    		totalNumTable[i] = (TextView) findViewById(timeStringToIdMap.// string to id map
    												get(stringTimeTable[i]));
    		groupNumTable[i]= (TextView) findViewById(timeGroupToIdMap.get(stringTimeTable[i]));
    		totalNumTable[i].setOnTouchListener(this);
    		// get  number of people attend this sport individually at the same date and time
    		num = planFunction.getIndividualNum(sportType, planDate,timeIdToTimeMap.get(timeStringToIdMap.get(stringTimeTable[i])));
    		// get list of group plan id of this sport at the same date and time
    		groupIdList = planFunction.getGroupIdList(sportType, planDate,timeIdToTimeMap.get(timeStringToIdMap.get(stringTimeTable[i])));
    		// including group plan owner in the total number
    		num = num+groupIdList.length;
    		if(groupIdList.length!=0){
	    		// get number of people attending the group plan at the same date and time
	    		for(int k=0; k<groupIdList.length;k++)
	    			num = num+planFunction.getGroupAttendingNum(groupIdList[k]);
    		}
    		totalNumTable[i].setText(""+num);
    		// check if a user created a group plan or accepted a group plan at this time
    		groupPlanId = planFunction.getGroupPlanIdAtSameTime(planDate, timeIdToTimeMap.get(timeStringToIdMap.get(stringTimeTable[i])), userInfo.get(Constants.USER_ID) );
    		if(groupPlanId!=0){ // have a match
    			// get total number of people invited
    			totalInvitedNum = planFunction.getInvitedNum(groupPlanId);
    			// get number of people accepted the invitation
    			acceptedNum = planFunction.getGroupAttendingNum(groupPlanId);
    			// show total/accepted including the owner
    			groupNumTable[i].setText((totalInvitedNum+1)+"/"+(acceptedNum+1));
    		}
    		else
    			groupNumTable[i].setText("-");
    	}
    }

    /**
     * show toast message on the screen
     * @param s message that user wants to show
     */
    public void show(String s){
    	//Toast.makeText(this, new StringBuilder().append("Date choosen is "+pYear+" "+(pMonth+1)+" "+pDay),  Toast.LENGTH_SHORT).show();
    	Toast.makeText(this, s,  Toast.LENGTH_LONG).show();

    }
    
    /**
     * method to get sport type when a button is pressed
     * @param view	button that is pressed
     */
    public void getText(View view){
    	// get sport type from the button
    	sportType = ((Button) view).getText().toString();
    	if(sportType.compareTo("Table Tennis")==0)
    		sportType="T-Tennis";
    	Log.d(Constants.LOG_PLAN_TAG,
				Messages.PLAN_ACTVITY_PICK_SPORT_TYPE+sportType);
    	// get the current date
    	this.getCurrentDate();
    	// continue to pick date
    	getDate();
    }
    
    /**
     * get the date of the plan activity
     */
    @SuppressWarnings("deprecation")
	public void getDate(){
    	setContentView(R.layout.pickdate);
    	TextView showSportType = (TextView) findViewById(R.id.pickedType);
		showSportType.setText(sportType+" >>");
    	final DatePicker datePicker = (DatePicker) findViewById(R.id.datePicker);
    	datePicker.updateDate(currentDate.getYear(), currentDate.getMonth(), currentDate.getDate());
    	final Button btn = (Button) findViewById(R.id.selectDate);
    	btn.setOnClickListener(new OnClickListener()
    	{
    		public void onClick(View v){
    			// update the date
    			Date tempDate = new Date (datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth());
    			Log.d(Constants.LOG_PLAN_TAG, tempDate.toString());
    			TextView errorMessage = (TextView) findViewById(R.id.errorMessage);
    			// plan date is in the pass
    			if(currentDate.after(tempDate))		
    				errorMessage.setText(Messages.PLAN_ACTVITY_DATE_IN_THE_PAST);
    			// current month is not December, but plan is in next year
    			else if (currentDate.getYear()!=tempDate.getYear()	
    					&&currentDate.getMonth()!=11)
    				errorMessage.setText(tempDate.getYear()+"/"+(tempDate.getMonth()+1)+"/"+tempDate.getDate()+
    						Messages.PLAN_ACTVITY_NOT_WITHIN_TWO_WEEKS+currentDate.getYear()+
    						"/"+(currentDate.getMonth()+1)+"/"+currentDate.getDate()+")");
    			// if it is not the last two week of the year
    			else if (currentDate.getYear()!=tempDate.getYear()	
    					&&currentDate.getMonth()==11&&currentDate.getDate()<17)
    				errorMessage.setText(tempDate.getYear()+"/"+(tempDate.getMonth()+1)+"/"+tempDate.getDate()+
    						Messages.PLAN_ACTVITY_NOT_WITHIN_TWO_WEEKS+currentDate.getYear()+
    						"/"+(currentDate.getMonth()+1)+"/"+currentDate.getDate()+")");
    			// same year but plan date is more than 1 month away from current month
    			else if (currentDate.getYear()==tempDate.getYear()
    					&&tempDate.getMonth()-currentDate.getMonth()>1)	
    					errorMessage.setText(tempDate.getYear()+"/"+(tempDate.getMonth()+1)+"/"+tempDate.getDate()+
        						Messages.PLAN_ACTVITY_NOT_WITHIN_TWO_WEEKS+currentDate.getYear()+
        						"/"+(currentDate.getMonth()+1)+"/"+currentDate.getDate()+")");
    			// same year, plan date is a month away from current date but date is more than two weeks different
    			else if (currentDate.getYear()==tempDate.getYear()	
    					&&tempDate.getMonth()-currentDate.getMonth()==1&&tempDate.getDate()-currentDate.getDate()>-17)
    				errorMessage.setText(tempDate.getYear()+"/"+(tempDate.getMonth()+1)+"/"+tempDate.getDate()+
    						Messages.PLAN_ACTVITY_NOT_WITHIN_TWO_WEEKS+currentDate.getYear()+
    						"/"+(currentDate.getMonth()+1)+"/"+currentDate.getDate()+")");
    			// same year, same month, but difference of date are greater than two weeks
    			else if (currentDate.getYear()==tempDate.getYear()	
    					&&currentDate.getMonth()==tempDate.getMonth()
    					&&tempDate.getDate()-currentDate.getDate()>14)
    				errorMessage.setText(tempDate.getYear()+"/"+(tempDate.getMonth()+1)+"/"+tempDate.getDate()+
    						Messages.PLAN_ACTVITY_NOT_WITHIN_TWO_WEEKS+currentDate.getYear()+
    						"/"+(currentDate.getMonth()+1)+"/"+currentDate.getDate()+")");
    			// plan date and current date is within two weeks
    			else if(planDate==null){
    				btn.setEnabled(false);
    				btn.setVisibility(0);							
    				planDate=tempDate;
    				// continue to pick time
        			setContentView(R.layout.picktime);
        			TextView currentPicked = (TextView) findViewById(R.id.pickTypeDate);
        			currentPicked.setText(sportType+" >> "+planDate.getYear()+"-"+
        			(planDate.getMonth()+1)+"-"+planDate.getDate()+" >>");
        	    	// create listener for time table
        	        createOnTouchListener();
    			}
    		}
    	});
    }
    
    /**
     * get current date
     */
    @SuppressWarnings("deprecation")
	public void getCurrentDate(){
        /** Get the current date */
        final Calendar cal = Calendar.getInstance();
        currentDate = new Date(cal.get(Calendar.YEAR), 
        		cal.get(Calendar.MONTH), 	// month from 0-11
        		cal.get(Calendar.DAY_OF_MONTH));
        Log.d(Constants.LOG_PLAN_TAG,currentDate.toString());
    }
    	  
    /**
     * match time from a string to time in hour, minute, second format
     */
    @SuppressWarnings("deprecation")
	public void matchTime(){
    	timeStringToIdMap = new HashMap <String, Integer>();
    	timeStringToIdMap.put(Constants.SIXAM, R.id.sixam);
    	timeStringToIdMap.put(Constants.SEVENAM, R.id.sevenam);
    	timeStringToIdMap.put(Constants.EIGHTAM, R.id.eightam);
    	timeStringToIdMap.put(Constants.NINEAM, R.id.nineam);
    	timeStringToIdMap.put(Constants.TENAM, R.id.tenam);
    	timeStringToIdMap.put(Constants.ELEVENAM, R.id.elevenam);
    	timeStringToIdMap.put(Constants.TWELVEPM, R.id.twelvepm);
    	timeStringToIdMap.put(Constants.ONEPM, R.id.onepm);
    	timeStringToIdMap.put(Constants.TWOPM, R.id.twopm);
    	timeStringToIdMap.put(Constants.THREEPM, R.id.threepm);
    	timeStringToIdMap.put(Constants.FOURPM, R.id.fourpm);
    	timeStringToIdMap.put(Constants.FIVEPM, R.id.fivepm);
    	timeStringToIdMap.put(Constants.SIXPM, R.id.sixpm);
    	timeStringToIdMap.put(Constants.SEVENPM, R.id.sevenpm);
    	timeStringToIdMap.put(Constants.EIGHTPM, R.id.eightpm);
    	timeStringToIdMap.put(Constants.NINEPM, R.id.ninepm);
    	timeStringToIdMap.put(Constants.TENPM, R.id.tenpm);
    	timeStringToIdMap.put(Constants.ELEVENPM, R.id.elevenpm);
    	
    	timeGroupToIdMap = new HashMap <String, Integer>();
    	timeGroupToIdMap.put(Constants.SIXAM, R.id.sixamgroup);
    	timeGroupToIdMap.put(Constants.SEVENAM, R.id.sevenamgroup);
    	timeGroupToIdMap.put(Constants.EIGHTAM, R.id.eightamgroup);
    	timeGroupToIdMap.put(Constants.NINEAM, R.id.nineamgroup);
    	timeGroupToIdMap.put(Constants.TENAM, R.id.tenamgroup);
    	timeGroupToIdMap.put(Constants.ELEVENAM, R.id.elevenamgroup);
    	timeGroupToIdMap.put(Constants.TWELVEPM, R.id.twelvepmgroup);
    	timeGroupToIdMap.put(Constants.ONEPM, R.id.onepmgroup);
    	timeGroupToIdMap.put(Constants.TWOPM, R.id.twopmgroup);
    	timeGroupToIdMap.put(Constants.THREEPM, R.id.threepmgroup);
    	timeGroupToIdMap.put(Constants.FOURPM, R.id.fourpmgroup);
    	timeGroupToIdMap.put(Constants.FIVEPM, R.id.fivepmgroup);
    	timeGroupToIdMap.put(Constants.SIXPM, R.id.sixpmgroup);
    	timeGroupToIdMap.put(Constants.SEVENPM, R.id.sevenpmgroup);
    	timeGroupToIdMap.put(Constants.EIGHTPM, R.id.eightpmgroup);
    	timeGroupToIdMap.put(Constants.NINEPM, R.id.ninepmgroup);
    	timeGroupToIdMap.put(Constants.TENPM, R.id.tenpmgroup);
    	timeGroupToIdMap.put(Constants.ELEVENPM, R.id.elevenpmgroup);
    	
    	timeIdToTimeMap = new HashMap <Integer, Time>();
    	timeIdToTimeMap.put(timeStringToIdMap.get(Constants.SIXAM), new Time(6,0,0));
    	timeIdToTimeMap.put(timeStringToIdMap.get(Constants.SEVENAM), new Time(7,0,0));
    	timeIdToTimeMap.put(timeStringToIdMap.get(Constants.EIGHTAM), new Time(8,0,0));
    	timeIdToTimeMap.put(timeStringToIdMap.get(Constants.NINEAM), new Time(9,0,0));
    	timeIdToTimeMap.put(timeStringToIdMap.get(Constants.TENAM), new Time(10,0,0));
    	timeIdToTimeMap.put(timeStringToIdMap.get(Constants.ELEVENAM),new Time(11,0,0));
    	timeIdToTimeMap.put(timeStringToIdMap.get(Constants.TWELVEPM), new Time(12,0,0));
    	timeIdToTimeMap.put(timeStringToIdMap.get(Constants.ONEPM), new Time(13,0,0));
    	timeIdToTimeMap.put(timeStringToIdMap.get(Constants.TWOPM), new Time(14,0,0));
    	timeIdToTimeMap.put(timeStringToIdMap.get(Constants.THREEPM), new Time(15,0,0));
    	timeIdToTimeMap.put(timeStringToIdMap.get(Constants.FOURPM), new Time(16,0,0));
    	timeIdToTimeMap.put(timeStringToIdMap.get(Constants.FIVEPM), new Time(17,0,0));
    	timeIdToTimeMap.put(timeStringToIdMap.get(Constants.SIXPM), new Time(18,0,0));
    	timeIdToTimeMap.put(timeStringToIdMap.get(Constants.SEVENPM), new Time(19,0,0));
    	timeIdToTimeMap.put(timeStringToIdMap.get(Constants.EIGHTPM), new Time(20,0,0));
    	timeIdToTimeMap.put(timeStringToIdMap.get(Constants.NINEPM), new Time(21,0,0));
    	timeIdToTimeMap.put(timeStringToIdMap.get(Constants.TENPM), new Time(22,0,0));
    	timeIdToTimeMap.put(timeStringToIdMap.get(Constants.ELEVENPM), new Time(23,0,0));
    	
    	stringTimeTable = new String[24];
   	 	stringTimeTable[6]=Constants.SIXAM;
   	 	stringTimeTable[7]=Constants.SEVENAM;
   	 	stringTimeTable[8]=Constants.EIGHTAM;
   	 	stringTimeTable[9]=Constants.NINEAM;
   	 	stringTimeTable[10]=Constants.TENAM;
   	 	stringTimeTable[11]=Constants.ELEVENAM;
   	 	stringTimeTable[12]=Constants.TWELVEPM;
   	 	stringTimeTable[13]=Constants.ONEPM;
   	 	stringTimeTable[14]=Constants.TWOPM;
   	 	stringTimeTable[15]=Constants.THREEPM;
   	 	stringTimeTable[16]=Constants.FOURPM;
   	 	stringTimeTable[17]=Constants.FIVEPM;
   	 	stringTimeTable[18]=Constants.SIXPM;
   	 	stringTimeTable[19]=Constants.SEVENPM;
   	 	stringTimeTable[20]=Constants.EIGHTPM;
   	 	stringTimeTable[21]=Constants.NINEPM;
   	 	stringTimeTable[22]=Constants.TENPM;
   	 	stringTimeTable[23]=Constants.ELEVENPM;
    	
    }
    
    /**
     * return the time
     * @param time string of the time 
     * @return time in the hour, minute, second format
     */
    public Time getTime(String time){
    	return timeIdToTimeMap.get(timeStringToIdMap.get(time));
    }
    
    /**
     * overload the getTime method
     * @param id id of the time slot
     * @return time in hour, minute, sec format
     */
    public Time getTime(Integer id){
    	return timeIdToTimeMap.get(id);
    }
        
	@SuppressWarnings("deprecation")
	@Override
	public boolean onTouch(View v, MotionEvent event) {
		String tempTime=null;
		switch(v.getId()){
		case R.id.sixam: tempTime=Constants.SIXAM;break;
		case R.id.sevenam: tempTime=Constants.SEVENAM;break;
		case R.id.eightam: tempTime=Constants.EIGHTAM;break;
		case R.id.nineam: tempTime=Constants.NINEAM;break;
		case R.id.tenam: tempTime=Constants.TENAM;break;
		case R.id.elevenam: tempTime=Constants.ELEVENAM;break;
		case R.id.twelvepm: tempTime=Constants.TWELVEPM;break;
		case R.id.onepm: tempTime=Constants.ONEPM;break;
		case R.id.twopm: tempTime=Constants.TWOPM;break;
		case R.id.threepm: tempTime=Constants.THREEPM;break;
		case R.id.fourpm: tempTime=Constants.FOURPM;break;
		case R.id.fivepm: tempTime=Constants.FIVEPM;break;
		case R.id.sixpm: tempTime=Constants.SIXPM;break;
		case R.id.sevenpm: tempTime=Constants.SEVENPM;break;
		case R.id.eightpm: tempTime=Constants.EIGHTPM;break;
		case R.id.ninepm: tempTime=Constants.NINEPM;break;
		case R.id.tenpm: tempTime=Constants.TENPM;break;
		case R.id.elevenpm: tempTime=Constants.ELEVENPM;break;
		default:;	// do nothing
		}
		// get the picked time
		Time pickedTime = timeIdToTimeMap.get(timeStringToIdMap.get(tempTime));
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
		String temp = sdf.format(Calendar.getInstance().getTime());
		// get hour, minute, second
		String[] hms = temp.split(":");
		Time nowTime = new Time(Integer.parseInt(hms[0]),Integer.parseInt(hms[1]),Integer.parseInt(hms[2]));
		if(currentDate.equals(planDate)&&(nowTime.after((pickedTime))))	// if picked time is in the past
			show(Messages.PLAN_ACTIVITY_TIME_IN_THE_PAST);
				
		else // time is in the future
			// if the user already made plan for the same date and time
			if(planFunction.checkConflectIndividualTime(planDate, timeIdToTimeMap.get(timeStringToIdMap.get(tempTime)), userInfo.get(Constants.USER_ID))
					||planFunction.checkConflectGroupCreatedTime(planDate, timeIdToTimeMap.get(timeStringToIdMap.get(tempTime)), userInfo.get(Constants.USER_ID))
					||planFunction.checkConflectGroupAcceptedTime(planDate, timeIdToTimeMap.get(timeStringToIdMap.get(tempTime)), userInfo.get(Constants.USER_ID))){
			show(Messages.PLAN_ACTIVITY_CONFLICT_DATE_TIME);
			Log.d(Constants.LOG_PLAN_TAG,Messages.PLAN_ACTIVITY_CONFLICT_DATE_TIME);
			}
			else{	// no conflict	
				// show final confirmation
				planTime = tempTime;
				Log.d(Constants.LOG_PLAN_TAG,Messages.PLAN_ACTIVITY_NO_CONFLICT);
				this.showConfirmation();		
			}
		return false;
	}
	
	/**
	 * show a confirmation page, also allow user to select among individual plan, group plan or cancel plan
	 */
	@SuppressWarnings("deprecation")
	public void showConfirmation(){
		setContentView(R.layout.confirmation);
		String outputMessage=null;
		TextView planEvent = new TextView(this);
		planEvent = (TextView) findViewById(R.id.planActivity);
		outputMessage = sportType+" "+planDate.getYear()+"/"+(planDate.getMonth()+1)+"/"+planDate.getDate()+" "+planTime;
		Log.d(Constants.LOG_PLAN_TAG ,Messages.PLAN_ACTVITY_FINAL_CONFIRMATION+outputMessage);
		planEvent.setText(outputMessage);
		
	}
	
	/**
	 * get action for the plan activity: individual? group? or cancel plan
	 * @param view	button view of the action
	 */
	public void getAction(View view){
		String action = null;
		action = ((Button) view).getText().toString();	// get the txt on the button
		try{
			

			if(action.equals("Individual")){	// if it is individual plan
				Log.d(Constants.LOG_PLAN_TAG,Messages.PLAN_ACTVITY_INDIVIDUAL_PLAN_CHOSEN);
				// insert the new individual plan into database
				planFunction.newIndividualPlan(sportType, planDate, timeIdToTimeMap.get(timeStringToIdMap.get(planTime)), userInfo.get(Constants.USER_ID));
				Log.d(Constants.LOG_DATABASE_TAG, Messages.DATABASE_NEW_INSERCT);
				// go back to home acitivty after the plan				
				Intent myIntent = null;
				Log.d(Constants.LOG_PLAN_TAG, Messages.PLAN_ACTIVITY_PLAN_ACTIVITY_END);
	    		myIntent = new Intent(PlanEventActivity.this, HomeActivity.class);
	    		startActivity(myIntent);
	    		finish();
			}
			else if (action.equals("Group")){	// if it is group plan
				String friendIdList[]=null, friendEmailList[]=null, friendNameList[]=null;
				Log.d(Constants.LOG_PLAN_TAG,Messages.PLAN_ACTVITY_GROUP_PLAN_CHOSEN);
				// get a list of friend id
				friendIdList = planFunction.getFriendIdList(userInfo.get(Constants.USER_ID));
				if(friendIdList==null){
					show("Need to add friends before you can plan a group activity");
				}
				else{
					// get a list of friend name and email
					friendNameList = planFunction.getFriendNameList(friendIdList);
					friendEmailList = planFunction.getFriendEmailList(friendIdList);
					// invite friends to the activity
					pickFriend(friendNameList, friendEmailList, friendIdList);
				}
						
			}
			else if (action.equals("Cancel")){	// cancel the operation and go back to the main page
				Log.d(Constants.LOG_PLAN_TAG, Messages.PLAN_ACTIVITY_CANCEL_PLAN); // do nothing if cancel select
			// after insert a plan or cancel the plan, go back to home screen
				Intent myIntent = null;
				Log.d(Constants.LOG_PLAN_TAG, Messages.PLAN_ACTIVITY_PLAN_ACTIVITY_END);
	    		myIntent = new Intent(PlanEventActivity.this, HomeActivity.class);
	    		startActivity(myIntent);
	    		finish();}
		}
		catch (Exception e){
			Log.d(Constants.LOGGER_ERROR_TAG,e.toString());
		}
		
		
	}
	
	/**
	 * pick friend from the friend list to invite to the activity
	 */
	public Boolean pickFriend(String[] friendNameList, String[] friendEmailList, String[] friendIdList){
		final PlanActivityFunctions planFunction = new PlanActivityFunctions();
		setContentView(R.layout.invitefriend);
		
		// find the layout that contain all the check boxes
		LinearLayout checkBoxLayout = (LinearLayout) findViewById(R.id.checkBoxLayout);
		// create list of check boxes to hold all the friends
		CheckBox [] friendList = new CheckBox[friendNameList.length];
		// txV is the text view to show total num of friend checked
		final TextView txV = (TextView) findViewById (R.id.showFriendNum);

		Button grpInvite = (Button) findViewById(R.id.groupInvite);
		grpInvite.setOnClickListener(new OnClickListener(){
			
			public void onClick(View v){
				if(invitedFriendList.size()==0){	// no friend invited
					show(Messages.PLAN_ACTIVITY_NO_FRIEND_INVITED);
				}
				else{	// have friend invited
					// insert the new group plan into database, return the group id
					String groupId=planFunction.newGroupPlan(sportType, planDate, timeIdToTimeMap.get(timeStringToIdMap.get(planTime)), userInfo.get(Constants.USER_ID));
					Log.d(Constants.LOG_DATABASE_TAG, Messages.DATABASE_NEW_INSERCT);
					// send request to invited friends
					planFunction.sendGroupRequest(userInfo.get(Constants.USER_ID), invitedFriendList, groupId);
					// go back to main page after creating a plan
					Intent myIntent = new Intent(PlanEventActivity.this, HomeActivity.class);
		    		startActivity(myIntent);
		    		Log.d("Constants.", Messages.PLAN_ACTIVITY_PLAN_ACTIVITY_END);
		    		finish();
				}
			}
		});		
		// iterate to create check box for each friend and add it to the layout
		for(int i=0;i<friendList.length;i++){
			friendList[i] = new CheckBox(this);
			// set the text of the check boxes
			friendList[i].setText(friendNameList[i]+"\n("+friendEmailList[i]+")");
			final String id = friendIdList[i];
			// create on click listener for the check box
			friendList[i].setOnCheckedChangeListener(new OnCheckedChangeListener()
			{
				private String friendId = id;
				@Override
				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
					if(isChecked){	// if a friend is checked
						// add to the invited friend list
						invitedFriendList.add(friendId);
						txV.setText("Number of friend selected: "+invitedFriendList.size());
					}
					else{// if a friend is unchecked
						// remove from the invited firend list
						invitedFriendList.remove(friendId);
						txV.setText("Number of friend selected: "+invitedFriendList.size());
					}
				}
			});
			// add the new checkbox into the check box layout
			checkBoxLayout.addView(friendList[i]);
		}
		return false;
	}
	
	public void onClick(View v){
		// do nothing
	}
}